from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from ship_segments.models import ShipSegment
from .models import CoupleSegment
from .serializers import ShipSegmentSerializer, CoupleSegmentImportSerializer


class CoupleSegmentListView(APIView):
    def get(self, request, format=None):
        # 获取分页参数
        page = request.query_params.get('current', 1)
        page_size = request.query_params.get('pageSize', 10)

        # 获取查询条件（可选）
        ship_number = request.query_params.get('ship_number', '').strip()
        ship_type = request.query_params.get('ship_type', '').strip()

        # 查询所有组合关系
        queryset = CoupleSegment.objects.all().order_by('couple_segment_id')

        # 过滤逻辑：根据 ship_number 或 ship_type 进行模糊匹配
        if ship_number or ship_type:
            filtered_ids = []
            for couple in queryset:
                try:
                    obj1 = ShipSegment.objects.get(ship_segments_id=couple.ship_segments_id)
                    obj2 = ShipSegment.objects.get(ship_segments_id=couple.combined_segment_id)

                    match = True
                    if ship_number:
                        match &= (
                            ship_number.lower() in obj1.ship_number.lower() or
                            ship_number.lower() in obj2.ship_number.lower()
                        )
                    if ship_type:
                        match &= (
                            ship_type.lower() in obj1.ship_type.lower() or
                            ship_type.lower() in obj2.ship_type.lower()
                        )

                    if match:
                        filtered_ids.append(couple.couple_segment_id)
                except ShipSegment.DoesNotExist:
                    continue  # 忽略无效记录

            queryset = queryset.filter(couple_segment_id__in=filtered_ids)

        # 分页处理
        paginator = Paginator(queryset, page_size)
        try:
            segments_page = paginator.page(page)
        except PageNotAnInteger:
            segments_page = paginator.page(1)
        except EmptyPage:
            segments_page = paginator.page(paginator.num_pages)

        result_list = []

        for couple in segments_page:
            try:
                obj1 = ShipSegment.objects.get(ship_segments_id=couple.ship_segments_id)
                obj2 = ShipSegment.objects.get(ship_segments_id=couple.combined_segment_id)
            except ShipSegment.DoesNotExist:
                continue  # 跳过无效关联的数据

            data1 = ShipSegmentSerializer(obj1).data
            data2 = ShipSegmentSerializer(obj2).data

            merged_data = {
                # 公共字段放在顶层
                "ship_number": obj1.ship_number,
                "ship_type": obj1.ship_type,

                # data1 的全部字段
                **data1,

                # data2 放在 coupleData 中
                "coupleData": data2
            }

            result_list.append(merged_data)

        return JsonResponse({
            "code": 200,
            "data": {
                "list": result_list,
                "total": paginator.count,
                "current": segments_page.number,
                "pageSize": page_size
            }
        }, status=status.HTTP_200_OK)


class BatchImportCoupleSegmentView(APIView):
    def post(self, request, *args, **kwargs):
        data_list = request.data.get('list', [])

        if not isinstance(data_list, list) or len(data_list) == 0:
            return JsonResponse({
                "code": 400,
                "message": "请传入有效的对象数组"
            }, status=status.HTTP_400_BAD_REQUEST)

        success_records = []
        error_records = []

        for idx, item in enumerate(data_list):
            serializer = CoupleSegmentImportSerializer(data=item)
            if serializer.is_valid():
                couple = serializer.save()
                if couple:  # 可能为 None（如果已存在）
                    success_records.append(couple)
            else:
                error_records.append({
                    "row_index": idx + 1,
                    "data": item,
                    "errors": serializer.errors
                })

        return JsonResponse({
            "code": 200,
            "message": f"成功导入 {len(success_records)} 条数据",
            "success_count": len(success_records),
            "failed_count": len(error_records),
            "errors": error_records
        }, status=status.HTTP_200_OK)